# 检查服域名访问状态
import requests
from zz import zz_return, zz_log, zz_str, zz_dingtalk, zz_redis, zz_code

log = zz_log.of()


# 格式：链接@过期日期;链接@过期日期
# https://app.lai-m.com/app/sys_status;https://app.ws.fjciecc.com/app/sys_status;https://lib.fjciecc.com/@2024-11-20;https://app.fubake.com/@2024-10-23;http://abc.test.com


def main():
    urls = zz_code.env('URL')
    url_arr = zz_str.split2(urls)
    print(url_arr)
    msg = ''
    exists_err_count = 0
    server_total = len(url_arr)
    #
    for item in url_arr:
        url = item[0]
        expire_time = None
        if len(item) > 1:
            expire_time = zz_code.date_from_str(item[1])

        domain = zz_code.url_domain(url)
        msg += f"**{domain}** \n\n"
        exists_err = False
        try:
            res = requests.get(url, timeout=3)
            if zz_str.contains(url, "/app/sys_status"):
                r = zz_return.parse(res.content)
                # 检查电脑状态
                rr = check_ok(r)
                if rr.err():
                    exists_err = True
                msg += rr.get_data("msg")
            else:
                if res.ok:
                    msg += "ok \n\n"
                else:
                    exists_err = True
                    msg += "error \n\n"
        except Exception as ex:
            log.error(ex)
            exists_err = True
            msg += f"访问异常 \n\n"

        if expire_time is not None:
            now = zz_code.date_add_day(zz_code.date_today(), 3)
            if now > expire_time:
                exists_err = True
                msg += f"过期时间：**{zz_code.date_tostring(expire_time, '%Y-%m-%d')}** \n\n"

        if exists_err:
            exists_err_count += 1

    send_jj = False  # 是否发提醒
    title = f"server ok: {server_total - exists_err_count}/{server_total}"
    if exists_err_count > 0:
        msg = f"### 检查服务器(*服务器存在异常*) \n\n {zz_code.date_tostring()} \n\n" + msg
        send_jj = True
    else:
        msg = f"### 检查服务器 \n\n  {zz_code.date_tostring()} \n\n" + msg
        redis = zz_redis.of()
        ok = redis.set_if_exists('task_sys_status_py', zz_code.date_tostring(), 60 * 60 * 5)
        log.info(f"redis if exists: {ok}")
        if ok:
            send_jj = True

    if send_jj:
        log.info(msg)
        zz_dingtalk.send_markdown(msg, title)


def check_ok(r: zz_return.Return):
    """
    检查系统状态是否正常
    :param r:
    :return:
    """
    redis_status = r.get_data("redis_status")
    redis_errmsg = r.get_data('redis_errmsg')
    mysql_status = r.get_data("mysql_status")
    mysql_errmsg = r.get_data('mysql_errmsg')

    msg = ""
    if redis_status:
        msg += "redis: ok \n\n"
    else:
        msg += "redis: **error** \n\n"
        msg += f"redis: {redis_errmsg}  \n\n"

    if mysql_status:
        msg += "mysql: ok \n\n"
    else:
        msg += "mysql: **error** \n\n"
        msg += f"mysql: {mysql_errmsg}  \n\n"

    rr = zz_return.of(123546, "")
    if redis_status and mysql_status:
        rr.set_errcode(0)

    rr.set_data("msg", msg)
    return rr


if __name__ == '__main__':
    main()
